use axum::Json;
use serde_json::Value;
use rsa::{RsaPrivateKey, pkcs1v15::SigningKey, sha2::Sha256, pkcs8::DecodePrivateKey, signature::{ Signer, SignatureEncoding }};

use crate::{base64, code, file};

// pub async fn sign_sha256( data:&str, private_key_path: &str) -> Result<String, Json<Value>> {

//     let key = get_key(private_key_path).await?;

//     let mut rng = rand::thread_rng();

//     let bits = 2048;
//     let private_key = RsaPrivateKey::new(&mut rng, bits).unwrap();
//     let signing_key = SigningKey::<Sha256>::new(private_key);
    
//     // Sign
//     let signature = signing_key.sign_with_rng(&mut rng, key.as_bytes()).to_vec();

//     Ok(base64::encode(signature))
// }
pub async fn sign_sha256(data:&str, private_key_path: &str) -> Result<String, Json<Value>> {

    let key = get_key(private_key_path).await?;

    let private_key = RsaPrivateKey::from_pkcs8_pem(&key);
    match private_key {
        Ok(f) => {
            let signing_key = SigningKey::<Sha256>::new(f);
            // Sign
            let signature = signing_key.sign(&mut data.as_bytes()).to_vec();
            Ok(base64::encode(signature))
        },
        Err(e) => Err(code::sys_(e.to_string()))
    }
}
async fn get_key(path: &str) -> Result<String, Json<Value>> {
    let key = file::create::open_file_read_to_str(path).await?;
    // let key = key
    // .replace("-----BEGIN PRIVATE KEY-----", "")
    // .replace("-----END PRIVATE KEY-----", "")
    // // .replace("-----BEGIN CERTIFICATE-----", "")
    // // .replace("-----END CERTIFICATE-----", "")
    // .replace("\n", "");
    Ok(key)
}